const token = localStorage.getItem('token')
const wsUrl = `${import.meta.env.VITE_WS_URL}?token=${token}`

class WebSocketService {
    //单例模式
    static instance = null

    constructor() {
        if (WebSocketService.instance) {
            return WebSocketService.instance // 直接返回已存在的实例
        }
        this.url = wsUrl
        this.socket = null
        this.onMessageCallback = null

        WebSocketService.instance = this // 保存实例
    }

    // 连接 WebSocket
    connect() {
        if (this.socket) {
            console.warn('WebSocket 已连接')
            return
        }

        this.socket = new WebSocket(this.url)

        this.socket.onopen = () => {
            console.log('WebSocket 连接成功')
        }

        this.socket.onmessage = (event) => {
            if (this.onMessageCallback) {
                this.onMessageCallback(JSON.parse(event.data))
            }
        }

        this.socket.onerror = (error) => {
            console.error('WebSocket 发生错误', error)
        }

        this.socket.onclose = () => {
            console.log('WebSocket 连接关闭')
            this.socket = null
        }
    }

    // 发送消息
    sendMessage(data) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(data))
        } else {
            console.warn('WebSocket 未连接，消息未发送')
        }
    }

    // 监听消息
    onMessage(callback) {
        this.onMessageCallback = callback
    }

    // 关闭连接
    disconnect() {
        if (this.socket) {
            this.socket.close()
        }
    }
}

export default WebSocketService
